using System.Collections.Generic;
using System.Linq;
using System.Net;

namespace UtilZ.Dotnet.Ex.Communication.Net.Base
{
    /// <summary>
    /// 网络通信限制器
    /// </summary>
    public class NetLimiter
    {
        private readonly EndPoint[] _whiteListEndPointList = null;
        private readonly EndPoint[] _blackListEndPointList = null;

#if NET4_0
        /// <summary>
        /// 白名单EndPoint列表
        /// </summary>
        public ICollection<EndPoint> WhiteListEndPointList
        {
            get { return this._whiteListEndPointList; }
        }
       
        /// <summary>
        /// 黑名单EndPoint列表
        /// </summary>
        public ICollection<EndPoint> BlackListEndPointList
        {
            get { return this._blackListEndPointList; }
        }
#else
        /// <summary>
        /// 白名单EndPoint列表
        /// </summary>
        public IReadOnlyList<EndPoint> WhiteListEndPointList
        {
            get { return this._whiteListEndPointList; }
        }

        /// <summary>
        /// 黑名单EndPoint列表
        /// </summary>
        public IReadOnlyList<EndPoint> BlackListEndPointList
        {
            get { return this._blackListEndPointList; }
        }
#endif


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="whiteListEndPointList">白名单EndPoint列表</param>
        /// <param name="blackListEndPointList">黑名单EndPoint列表</param>
        public NetLimiter(IEnumerable<EndPoint> whiteListEndPointList, IEnumerable<EndPoint> blackListEndPointList)
        {
            if (whiteListEndPointList != null)
            {
                this._whiteListEndPointList = whiteListEndPointList.ToArray();
            }

            if (blackListEndPointList != null)
            {
                this._blackListEndPointList = blackListEndPointList.ToArray();
            }
        }

        /// <summary>
        /// 检查EndPoint是否被限制,被限制返回true,未被限制返回false
        /// </summary>
        /// <param name="endPoint">用于检查的目标EndPoint</param>
        /// <returns>被限制返回true,未被限制返回false</returns>
        public bool Check(EndPoint endPoint)
        {
            if (this._blackListEndPointList != null &&
                this._blackListEndPointList.Any(t => { return t.Equals(endPoint); }))
            {
                //在黑名单中
                return true;
            }

            if (this._whiteListEndPointList == null ||
                this._whiteListEndPointList.Length == 0 ||
                this._whiteListEndPointList.Any(t => { return t.Equals(endPoint); }))
            {
                //白名单为null或为空或在白名单中
                return false;
            }
            else
            {
                //不在白名单中
                return true;
            }
        }

    }

}